package com.igeek.collateral.service.Impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.Month;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.igeek.collateral.entity.*;
import com.igeek.collateral.mapper.*;
import com.igeek.collateral.service.ICollateralService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.igeek.collateral.utils.QiniuUtils;
import com.igeek.collateral.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 押品资产信息 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-07-04
 */
@Service
public class CollateralServiceImpl extends ServiceImpl<CollateralMapper, Collateral> implements ICollateralService {

    @Autowired
    private InboundMapper inboundMapper;

    @Autowired
    private CollateralMapper collateralMapper;

    @Autowired
    private OutboundMapper outboundMapper;

    @Autowired
    private AssessMapper assessMapper;

    @Autowired
    private CollateralImagesMapper collateralImagesMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    //押品的总记录数（包括每天对应的出入库的数量）
    public static final String AllNum="AllNum::";
    //分页查询
    @Transactional
    @Override
    public Page<Collateral> findPage(PageQueryVO vo) {
        Integer currentPage = vo.getCurrentPage();
        Integer pageSize = vo.getPageSize();
        String queryString = vo.getQueryString();
        //封装Page对象
        Page<Collateral> page = new Page<>(currentPage , pageSize);
        //封装查询条件(根据押品名和押品信息类别,编码查询)
        LambdaQueryWrapper<Collateral> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .like(StringUtils.hasLength(queryString),Collateral::getName,queryString)
                .or()
                .eq(StringUtils.hasLength(queryString),Collateral::getInfoType,queryString)
                .or()
                .like(StringUtils.hasLength(queryString),Collateral::getCode,queryString);
        //执行分页查询条件
        Page<Collateral> pageC = this.baseMapper.selectPage(page,lambdaQueryWrapper);
        return pageC;
    }

    //根据id删除
    @Transactional
    @Override
    public boolean delete(Long id) {
        LambdaQueryWrapper<Collateral> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Collateral::getId,id);
        int i=this.baseMapper.delete(lambdaQueryWrapper);
        return i>0?true:false;
    }


    //一对多删除
    @Override
    public boolean deleteAll(Integer id) {
        LambdaQueryWrapper<Inbound> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Outbound> lambdaQueryWrapper1=new LambdaQueryWrapper<>();
        LambdaQueryWrapper<CollateralImages> lambdaQueryWrapper2=new LambdaQueryWrapper<>();
        //LambdaQueryWrapper<History> lambdaQueryWrapper3=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Inbound::getCollateralId,id);
        lambdaQueryWrapper1.eq(Outbound::getCollateralId,id);
        lambdaQueryWrapper2.eq(CollateralImages::getCollateralId,id);
        //先删除所有表中的
        inboundMapper.delete(lambdaQueryWrapper);
        outboundMapper.delete(lambdaQueryWrapper1);
        collateralImagesMapper.delete(lambdaQueryWrapper2);
        //再删除自己的
        int i = this.baseMapper.deleteById(id);
        return i>0?true:false;

    }



    //饼状图的实现
    //select asset_type ,count(*) sum from collateral GROUP BY asset_type
    @Override
    public List<PieVO> getPieMess() {
        //定义List集合存放各类型对应的押品数量
        // 拿到资产类别对应的押品数量
        List<Long>longs=new ArrayList<>();
        for (int i = 1; i <10 ; i++) {
            Long l = this.baseMapper.selectCount(new LambdaQueryWrapper<Collateral>().eq(Collateral::getAssetType, i));
            longs.add(l);
        }

        //对象封装好传入List中
        List<PieVO> pieVOList = new ArrayList<>();
        pieVOList.add(new PieVO("土地", longs.get(0)));
        pieVOList.add(new PieVO("厂房", longs.get(1)));
        pieVOList.add(new PieVO("商用房", longs.get(2)));
        pieVOList.add(new PieVO("住房", longs.get(3)));
        pieVOList.add(new PieVO("机器设备", longs.get(4)));
        pieVOList.add(new PieVO("交通运输工具", longs.get(5)));
        pieVOList.add(new PieVO("股权", longs.get(6)));
        pieVOList.add(new PieVO("存货", longs.get(7)));
        pieVOList.add(new PieVO("其他资产种类", longs.get(8)));
        return pieVOList;
    }


    //折现图的实现
    @Override
    public ZheVo getZheMess() {
        Object o = redisTemplate.opsForValue().get(AllNum);
//        System.out.println(o);
        List<Map<String,InOutNumberVo>> mapList= (List<Map<String, InOutNumberVo>>) o;
        List<String> Slist=new ArrayList<>();
        List<Integer> IList=new ArrayList<>();
        List<Integer> OList=new ArrayList<>();
        //创建SimpleDateFormat对象，定义日期格式
        //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for(Map<String,InOutNumberVo> map:mapList)
        {
          Set<String> set=map.keySet();
            if(!ObjectUtils.isEmpty(set)) {
                Iterator<String> iterator=set.iterator();
                while(iterator.hasNext()){
                    String s = iterator.next();
                       //有数据的才渲染过来
                        if(!(map.get(s).getInNumber()==0&&map.get(s).getOutNumber()==0)) {
                            InOutNumberVo inOutNumberVo = map.get(s);
                            //拿到有数据的天数和对应的进库出库数据，放在集合中
                            Slist.add(s);
                            IList.add(inOutNumberVo.getInNumber());
                            OList.add(inOutNumberVo.getOutNumber());
                        }
                }
            }
        }
        //再将拿完好的数据的List,封装好ZheVo对象
        ZheVo zheVo=new ZheVo();
        zheVo.setDate(Slist);
        zheVo.setOutboundNum(OList);
        zheVo.setInboundNum(IList);
        return zheVo;
    }


    //七牛云上传图片
    @Override
    public String uploadByQiniuyun(MultipartFile imgFile) throws IOException {
        if(imgFile!=null){
            String oldName = imgFile.getOriginalFilename();
            if(StringUtils.hasLength(oldName)){
                String newName = UUID.randomUUID()+oldName;
                //上传至七牛云服务器
                InputStream inputStream =imgFile.getInputStream();
                String pic = QiniuUtils.uploadForQiniu(inputStream, newName);
                return pic;
            }
        }
        return null;
    }


    //只查询待审核的
    @Override
    public Page<Collateral> findPageAss(PageQueryVO vo) {
        Integer currentPage = vo.getCurrentPage();
        Integer pageSize = vo.getPageSize();
        String queryString = vo.getQueryString();
        //封装Page对象
        Page<Collateral> page = new Page<>(currentPage , pageSize);
        //封装查询条件()
        LambdaQueryWrapper<Collateral> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .like(StringUtils.hasLength(queryString),Collateral::getName,queryString)
                .or()
                .eq(Collateral::getStatus,0);
        //执行分页查询条件
        Page<Collateral> pageC = this.baseMapper.selectPage(page,lambdaQueryWrapper);
        return pageC;
    }




    //只查询待评估的,正常入库，置换入库,
    @Override
    public Page<Collateral> findPageQ(PageQueryVO vo) {
        Integer currentPage = vo.getCurrentPage();
        Integer pageSize = vo.getPageSize();
        String queryString = vo.getQueryString();
        //封装Page对象
        Page<Collateral> page = new Page<>(currentPage , pageSize);
        //封装查询条件(点击申请入库，此时所有的押品状态应该为:已完成评估)
        LambdaQueryWrapper<Collateral> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .like(StringUtils.hasLength(queryString),Collateral::getName,queryString)
                .or()
                .eq(Collateral::getStatus,3)
                .or()
                .eq(Collateral::getStatus,6)
                .or()
                .eq(Collateral::getStatus,5);
        //执行分页查询条件
        Page<Collateral> pageC = this.baseMapper.selectPage(page,lambdaQueryWrapper);
        return pageC;
    }




    //点击同意后，在评估报告中加入一条信息
    @Override
    public boolean updateS(Collateral co) {
            //同时像评估报告中添加一条信息,并将评估报告中的状态也修改为待评估
            Assess assess = new Assess();
            assess.setCode(UUID.randomUUID().toString());
            assess.setCollateralId(co.getId());
            assess.setStatus(co.getStatus());
            assessMapper.insert(assess);
            this.baseMapper.updateById(co);
        return false;
    }


    //点击驳回后，将状态修改为审核为通过，就不需要在评估报告中显示
    @Override
    public boolean updateDS(Collateral co) {
        //审核未通过
        co.setStatus(2);
        int i = collateralMapper.updateById(co);
        return i>0?true:false;
    }



    //拿到柱状图的信息
    @Override
    public ColumnVo getColumnMess() {
        ColumnVo columnVo=new ColumnVo();
        //押品中的押品名,估值，最终价值

        List<Collateral> collaterals = this.baseMapper.selectList(null);
        //拿到所有的押品后按照自己的需求来安排(获取2024年编辑的押品)
        List<Collateral> newColl=new ArrayList<>();
            if(!CollectionUtils.isEmpty(collaterals)) {
                collaterals.forEach(coll -> {
                    if (!ObjectUtils.isEmpty(coll.getApplyTime())) {
                        String s = coll.getApplyTime().toString();
                        boolean b = s.endsWith("2024");
                        if (b) {
                            newColl.add(coll);
                        }
                    }
                });
            }
        Set<String> mouthL=new HashSet<>();
        List<Double> lastV=new ArrayList<>();
        List<Double> endV=new ArrayList<>();
        Set<Integer> monthF=new HashSet<>();
        //再将月份分析一下，把相同月份的押品的最新估值放在一起，最终估值放在一起
        newColl.forEach(coll->{
            if(!ObjectUtils.isEmpty(coll.getApplyTime()))
            {
                int a=DateUtil.month(coll.getApplyTime());
                if((!ObjectUtils.isEmpty(a))&&(!ObjectUtils.isEmpty(coll.getLatestValue()))&&(!ObjectUtils.isEmpty(coll.getReferencePrice())))
                {
                    //放入假的月份集合中,为了后面的遍历拿去这个月的信息
                    monthF.add(a);
                    //拿到对用的月份，放在月份的集合中,因为mount从0开始取的
                Integer trueMonth = (a+1);
                String mon = trueMonth.toString();
                String month=mon+"月份";
                    //将月份放入
                    mouthL.add(month);
               }
            }
        });
        //遍历这个月份集合中的所有天数，将押品的最新估值价和处置参考价都计算出来
        monthF.forEach(mon->{
            double sumLastV=0.0;
            double sumEndV=0.0;
            if(!ObjectUtils.isEmpty(mon))
            {
                //
                for (int i = 0; i < newColl.size(); i++) {
                    if(!ObjectUtils.isEmpty(newColl.get(i))&&mon==DateUtil.month(newColl.get(i).getApplyTime()))
                    {
                        Collateral coll=newColl.get(i);
                        //如果符合，就放入价值信息++的
                        if((!ObjectUtils.isEmpty(coll.getLatestValue()))&&(!ObjectUtils.isEmpty(coll.getReferencePrice()))) {
                            sumLastV += coll.getLatestValue();
                            sumEndV += coll.getReferencePrice();
                        }
                    }
                }
                lastV.add(sumLastV);
                endV.add(sumEndV);
            }
        });
        columnVo.setMouth(mouthL);
        columnVo.setLastValue(lastV);
        columnVo.setEndValue(endV);
        return columnVo;
    }


    //
    @Override
    public HistoryMessVo getHMess(Long id) {
        Collateral collateral = collateralMapper.selectById(id);
        HistoryMessVo historyMessVo=new HistoryMessVo();
        //拿到申请人，申请时间，审核人，审核时间
        historyMessVo.setApplyTime(collateral.getApplyTime());

        //拿到押品状态
        Integer status = collateral.getStatus();
        for(int i=0;i<=status;i++)
        {

        }


        return null;
    }


    //统计当前押品的进库总记录以及出库总记录数
    @Override
    public InOutAllNumVo getTopMess() {
        List<Collateral> collaterals = this.baseMapper.selectList(null);
        //判断当前押品的状态，当处于在入库时，进库记录加一，当处于在出库时，出库记录加一
        InOutAllNumVo inOutAllNumVo=new InOutAllNumVo();
        int ICount=0;
        int OCount=0;
        Iterator<Collateral> iterator=collaterals.iterator();
        while(iterator.hasNext())
        {
            Collateral collN = iterator.next();
            if(collN.getStatus()==5||collN.getStatus()==6)
            {
                //进库记录++
                ICount++;
            }
            else if(collN.getStatus()==8||collN.getStatus()==9||collN.getStatus()==10)
            {
                //出库记录++
                OCount++;
            }
        }
        inOutAllNumVo.setInAllNumber(ICount);
        inOutAllNumVo.setOutAllNumber(OCount);
        return inOutAllNumVo;
    }


}
